<?php
namespace app\api\controller;
use think\Db;
class Ucenter
{
  public function wxLogin()
  {
    $APPID = "wx849f8981a8bb56ed";
    $SECRET = "c19328b1b93263724405058c4754244b";
    $code = input("code");
    

   $URL = "https://api.weixin.qq.com/sns/jscode2session";
   $data = ["appid" =>$APPID,"secret" => $SECRET ,"js_code" =>$code ,"grant_type" => "authorization_code"];
   $result = json_decode($this->httpRequest($URL, $data),true);
   $openId = $result['openid'];
   $userInfo = Db::name("user")->where("openid",$openId)->find();
     $sessionKey = md5(rand(10000,99999).time());
    if($userInfo){
      cache($sessionKey,  $openId);
      return json(["code" => 0 ,"sessionKey" =>$sessionKey]);
      
    }else{
      $username = "wx" .rand(1000000,9999999);
      $userInfo = Db::name("user")->insert(["openid" => $openId,"username" => $username,"create_time" =>time()]);
      if($userInfo){
          cache($sessionKey,  $openId);
          return json(["code" => 0 ,"sessionKey" =>$sessionKey]);
      }
    }
  }
  
  public function httpRequest($url,$data = null,$headers=array()){
    $curl = curl_init();
    if( count($headers) >= 1 ){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_URL, $url);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}
}